﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Diagnostics;
using Nancy;
using Nancy.Responses;
using Nancy.Routing;
using Nancy.Security;
using System.IO;

namespace wms_service.Module
{
    public class DownloadModule : NancyModule
    {
        public DownloadModule(IRootPathProvider pathProvider) :base("/download")
        {
            Get["/pc/filelist"] = p =>
            {
                string remoteDir = pathProvider.GetRootPath() + $"/content/pcupdate";

                string[] filelist = Directory.GetFiles(remoteDir);

                Dictionary<string, dynamic> fileinfoList = new Dictionary<string, dynamic>();

                fileinfoList.Add("FileCount", filelist.Length);

                List<dynamic> fileInfos = new List<dynamic>();

                foreach (var file in filelist)
                {
                    FileInfo f = new FileInfo(file);

                    fileInfos.Add(new
                    {
                        Name = f.Name,
                        FullName = f.FullName,
                        Modified = f.LastWriteTime,
                        Size = f.Length
                    });
                }

                fileinfoList.Add("Files",fileInfos);

                return Response.AsJson(fileinfoList);
            };

            Get["/pc"] = p =>
            {
                string filename = pathProvider.GetRootPath() + $"/content/pcupdate/{Request.Query["filename"]}";

                if (!File.Exists(filename))
                {
                    return Response.AsJson(filename + " 不存在.");
                }

                return Response.AsFile(filename);
            };

            Get["/env/{file}"] = p =>
            {
                string filename = pathProvider.GetRootPath() + $"content/environment/{(string)p.file}";

                if (!File.Exists(filename))
                {
                    return Response.AsJson(filename + " 不存在.");
                }

                return Response.AsFile(filename);
            };

            Get["/client/{file}"] = p =>
            {
                string filename = pathProvider.GetRootPath() + $"/content/clientsetup/{(string)p.file}";

                if (!File.Exists(filename))
                {
                    return Response.AsJson(filename + " 不存在.");
                }

                return Response.AsFile(filename);
            };
        }

    }
}